/**
 * Copyright (c) 2018, dreamkaylee@foxmail.com All Rights Reserved.
 */

package com.common.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.io.HTMLWriter;
import org.dom4j.io.OutputFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

/**
 * HTML工具类
 * @author limk
 * @date 2018年2月12日 下午8:44:52
 * @version 1.0
 */
public class HtmlUtil {
	
	private static final String AJAX = "XMLHttpRequest";
	private static final String FROM = "application/x-www-form-urlencoded";
	
	/**
	 * 是否是Ajax请求
	 * @param request
	 * @return
	 */
	public static boolean isAjaxRequest(HttpServletRequest request) {
		String requestedWith = request.getHeader("X-Requested-With");
		if (requestedWith != null && requestedWith.equalsIgnoreCase(AJAX)) {
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * 是否是From请求
	 * @param request
	 * @return
	 */
	public static boolean isFromRequest(HttpServletRequest request) {
		String requestedWith = request.getHeader("Content-Type");
		if (requestedWith != null && requestedWith.equalsIgnoreCase(FROM)) {
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * 返回json
	 * @param response
	 * @param result
	 */
	public static void writeJson(HttpServletResponse response, String result) {
		// 设置状态码
		response.setStatus(HttpStatus.OK.value());
		// 设置ContentType
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        // 避免乱码
        response.setCharacterEncoding("UTF-8"); 
        response.setHeader("Cache-Control", "no-cache, must-revalidate");
		PrintWriter out;
		try {
			out = response.getWriter();
			out.write(result);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
	
	/**
	 * 除去HTML标签
	 * @param str
	 * @return
	 */
	public static String removeHTMLLableExe(String str) {
		str = StringUtil.stringReplace(str, ">\\s*<", "><");
		// 去掉页面上看不到的字符
		str = StringUtil.stringReplace(str, "\\s", "");
		// 替换空格
		str = StringUtil.stringReplace(str, "&nbsp;", " ");
		// 去<br><br />
		str = StringUtil.stringReplace(str, "<br ?/?>", "\n");
		// 去掉<>内的字符
		str = StringUtil.stringReplace(str, "<([^<>]+)>", "");
		// 将多个空白变成一个空格
		str = StringUtil.stringReplace(str, "\\s\\s\\s*", " ");
		// 去掉头的空白
		str = StringUtil.stringReplace(str, "^\\s*", "");
		// 去掉尾的空白
		str = StringUtil.stringReplace(str, "\\s*$", "");
		str = StringUtil.stringReplace(str, " +", " ");
		return str;
	}

	/**
	 * 去掉HTML标签之外的字符串
	 * @param str
	 * @return
	 */
	public static String removeOutHTMLLable(String str) {
		str = StringUtil.stringReplace(str, ">([^<>]+)<", "><");
		str = StringUtil.stringReplace(str, "^([^<>]+)<", "<");
		str = StringUtil.stringReplace(str, ">([^<>]+)$", ">");
		return str;
	}

	/**
	 * 将html的省略写法替换成非省略写法
	 * @param str html字符串
	 * @param pt 标签, 如:table
	 * @return
	 */
	public static String fomateToFullForm(String str, String pt) {
		String regEx = "<" + pt + "\\s+([\\S&&[^<>]]*)/>";
		Pattern p = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
		Matcher m = p.matcher(str);
		String[] sa = null;
		String sf = "";
		String sf2 = "";
		String sf3 = "";
		for (; m.find();) {
			sa = p.split(str);
			if (sa == null) {
				break;
			}
			sf = str.substring(sa[0].length(), str.indexOf("/>", sa[0].length()));
			sf2 = sf + "></" + pt + ">";
			sf3 = str.substring(sa[0].length() + sf.length() + 2);
			str = sa[0] + sf2 + sf3;
			sa = null;
		}
		return str;
	}

	/**
	 * 用要通过URL传输的内容进行编码
	 * @param src
	 * @return
	 */
	public static String urlEncode(String src) {
		String value = "";
		try {
			if (src != null) {
				value = URLEncoder.encode(src, "GBK");
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			value = src;
		}

		return value;
	}

	/**
	 * 解析前台encodeURIComponent编码后的参数
	 * @param property
	 * @return
	 */
	public static String getEncodePra(String property) {
		String trem = "";
		if (StringUtil.isNotEmpty(property)) {
			try {
				trem = URLDecoder.decode(property, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		return trem;
	}

	/**
	 * html 必须是格式良好的
	 * @param str
	 * @return
	 * @throws Exception
	 */
	public static String formatHtml(String str) throws Exception {
		Document document = null;
		document = DocumentHelper.parseText(str);
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("utf-8");
		StringWriter writer = new StringWriter();
		HTMLWriter htmlWriter = new HTMLWriter(writer, format);
		htmlWriter.write(document);
		htmlWriter.close();
		return writer.toString();
	}
	
}
